[id].ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { defineEventHandler, EventHandlerRequest } from 'h3';
  2. import { DB } from '~~/server/db/DB';
  3. import { createErrorResponse, createSuccessResponse, IResponse } from '~~/server/utils/response';
  4. import { IChannel } from '../channel/[id]';
  5. export interface IArticle {
  6. id: number;
  7. model_id: number;
  8. channel_id: number;
  9. title: string;
  10. desc: string;
  11. image: string,
  12. video?: string,
  13. document_file?: string,
  14. images: string;
  15. seotitle: string;
  16. keywords: string;
  17. description: string;
  18. tags: string;
  19. diyname: string;
  20. publishtime: number;
  21. createtime: number;
  22. views: number;
  23. content: string;
  24. channel: IChannel;
  25. outlink?: string;
  26. }
  27. export default defineEventHandler<EventHandlerRequest, Promise<IResponse<IArticle>>>(async (event) => {
  28. try {
  29. const id = event.context.params?.id;
  30. if (!id)
  31. return createErrorResponse('分类ID不能为空');
  32. const article = await DB.table('pr_cms_archives')
  33. .where('id', id)
  34. .whereNull('deletetime')
  35. .where('status', 'normal')
  36. .first();
  37. if (!article)
  38. return createErrorResponse('文章不存在');
  39. const channel = await DB.table('pr_cms_channel')
  40. .where('id', article.channel_id)
  41. .first();
  42. if (!channel)
  43. return createErrorResponse('分类不存在');
  44. article.channel = channel;
  45. // 2. 通过model_id从pr_cms_model表中获取table字段
  46. const model = await DB.table('pr_cms_model')
  47. .where('id', article.model_id)
  48. .select('table')
  49. .first();
  50. if (!model)
  51. return createErrorResponse('分类不存在');
  52. // 3. 通过table指定的表通过id查出content
  53. const content = await DB.table(`pr_${model.table}`)
  54. .where('id', id)
  55. .select('content')
  56. .first();
  57. // 4. 合并返回结果
  58. if (content && content['content']) {
  59. article.content = content['content'];
  60. }
  61. return createSuccessResponse(article);
  62. } catch (error) {
  63. return createErrorResponse(error);
  64. }
  65. });